package com.jala.base;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PermissionFilter implements Filter {
    static Log logger = LogFactory.getLog(PermissionFilter.class);

    protected FilterConfig filterConfig;

    private static final String MAX_ACTIVE_TIME_KEY = "maxActiveTime";

    private ServletContext servletContext;
    private int maxActiveTime = 60*30;//秒

    private List<String> unFilterUrlPatterns;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        servletContext = filterConfig.getServletContext();
        String matString = filterConfig.getInitParameter(MAX_ACTIVE_TIME_KEY);
        if(StringUtils.isNotEmpty(matString)){
            maxActiveTime = Integer.valueOf(matString);
        }
        unFilterUrlPatterns=new ArrayList<String>();
        unFilterUrlPatterns.add("/wx/[a-z]+.htm");
        unFilterUrlPatterns.add("/wx/[a-z]+/[a-z]+.htm");
        unFilterUrlPatterns.add("/wx/[a-z]+/[a-z]+.htm");
        unFilterUrlPatterns.add("/wx/[a-z]+.json");
        unFilterUrlPatterns.add("/wx/[a-z]+/[a-z]+.json");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String contextPath = request.getContextPath();
        String requestUri = request.getRequestURI().replaceFirst(contextPath, "");
//        WxSessionHttpServletRequestWrapper sessionHttpServletRequestWrapper = new WxSessionHttpServletRequestWrapper(httpServletRequest, this.maxActiveTime, this.servletContext);

        //白名单 URL
        String ignoreRequestUri[] = {
                "/htdocs/",
                "/wx/login.htm"//登录
        };

        requestUri=requestUri.toLowerCase();
        for (String uri : ignoreRequestUri) {
            if (requestUri.endsWith(uri)||requestUri.startsWith(uri)) {
                chain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        HttpSession session=((HttpServletRequest) servletRequest).getSession();
        boolean checkSession=false;
        for(String uri:unFilterUrlPatterns){
            if(requestUri.matches(uri)){
                checkSession=true;
                break;
            }
        }
        if(checkSession){
            //if (session == null||session.getAttribute(Global.USER_SESSEION_KEY)==null) {
            if (session == null) {
                response.sendRedirect(contextPath + "/wx/login.htm");
                return;
            }else{
                chain.doFilter(servletRequest, servletResponse);
            }
        }else{
            chain.doFilter(servletRequest, servletResponse);
        }

    }


    @Override
    public void destroy() {
        logger.info(" destoy(), targetFilterLifecycle setted in web.xml for securityFilter");
    }

    /**
     * 将当前请求的url与权限配置进行匹配
     *
     * @param url
     * @return
     */
//    private boolean isMatch(String url) {
//        int userId = ShiroUtil.getPrincipalId();
//        List<String> urlPerms = umfManager.getUrlPerms(userId);
//        if (urlPerms != null && urlPerms.size() > 0) {
//            for (String urlPerm : urlPerms) {
//                if (urlPerm.equals(url)) {//完全匹配
//                    return true;
//                } else if (Pattern.matches(urlPerm, url)) {//正则匹配
//                    return true;
//                }
//            }
//        }
//        return false;
//    }

}
